/*
 * Hidden Equity LLC
 * Author: Maksym Fedyay, Kyiv, mcsimf@gmail.com
 * Date: 29.02.2012
 */

package com.hiddenequity.acts;

import java.util.ArrayList;
import java.util.Map;

import com.hiddenequity.adextensions_service.CampaignAdExtensionResponseParser;
import com.hiddenequity.adextensions_service.CampaignAdExtensionService;
import com.hiddenequity.utils.AppPreferences;
import com.hiddenequity.utils.AuthService;
import com.hiddenequity.utils.Communication;
import com.hiddenequity.utils.DateProcessor;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

public class Act_LocationExtensionList extends Act_Super{

	private String selectedCampaignId;
	private String selectedCampaignName;
	
	private static ArrayList<Map<String, String>> locationExtensionList = new ArrayList<Map<String, String>>();
	
	private Spinner spinnerDateRange;
	private Spinner spinnerStatus;
	private ListView lv;
	
	
	
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}

	
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.act_locationextension_list);

		title.setText(R.string.title_locationextension_list);
		sub_title.setVisibility(View.GONE);
		//filter.setVisibility(View.GONE);
		
		
		spinnerDateRange = (Spinner) findViewById(R.id.spin_CampaignDateRange);
		dateRangeItem = AppPreferences.LoadPreferenceInt("dateRange", 0,
				getApplication());
		inflateSpinner(spinnerDateRange, R.array.arr_dateRanges, dateRangeItem);

		spinnerDateRange
				.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
					public void onItemSelected(AdapterView<?> parent,
							View view, int pos, long id) {
						try {
							if (pos != dateRangeItem) {
								AppPreferences.SavePreferenceInt("dateRange",
										pos, getApplication());
								dateRangeItem = pos;
								runOperationAsync(OPERATION_GET_LIST, getString(R.string.progress_loading), false);
							}
						} catch (Exception e) {
							e.printStackTrace();
						}

					}

					public void onNothingSelected(AdapterView<?> parent) {
					}

				});

		// Populate status list
		spinnerStatus = (Spinner) findViewById(R.id.spin_CampaignStatus);
		statusItem = AppPreferences.LoadPreferenceInt("extensionstatus", 0, getApplication());
		inflateSpinner(spinnerStatus, R.array.arr_status_short1, statusItem);
		spinnerStatus
				.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
					public void onItemSelected(AdapterView<?> parent,
							View view, int pos, long id) {
						try {
							
							if (pos != statusItem) {
								AppPreferences.SavePreferenceInt("extensionstatus", pos,
										getApplication());
								statusItem = pos;
								runOperationAsync(OPERATION_GET_LIST, getString(R.string.progress_loading), false);
							}
						} catch (Exception e) {
							e.printStackTrace();
						}

					}

					public void onNothingSelected(AdapterView<?> parent) {
					}

				});
		
		//Set adapter and context menu for listview
		lv = (ListView) findViewById(R.id.list_locationextension);
		lv.setAdapter(locationExtensionListAdapter);
		registerForContextMenu(lv);

		lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
				Map<String, String> itemMap = (Map<String, String>) lv.getItemAtPosition(position);
				if(!itemMap.get("status").equals("DELETED") && listenExtensionListSelection){
					
					listenExtensionListSelection = false;
					
					stripActivity(listenExtensionListSelection, lv);
					
					Intent intent = new Intent(getBaseContext(), Act_LocationExtensionOperation.class);
					intent.putExtra("campaignId", selectedCampaignId);
					intent.putExtra("campaignName",	selectedCampaignName);

					intent.putExtra("companyName", itemMap.get("companyName"));
					intent.putExtra("streetAddress", itemMap.get("streetAddress"));
					intent.putExtra("streetAddress2", itemMap.get("streetAddress2"));
					intent.putExtra("cityName", itemMap.get("cityName"));
					intent.putExtra("postalCode", itemMap.get("postalCode"));
					intent.putExtra("countryCode", itemMap.get("countryCode"));
					intent.putExtra("provinceName", itemMap.get("provinceName"));
					intent.putExtra("phoneNumber", itemMap.get("phoneNumber"));

					startActivityForResult(intent, REQUEST_REFRESH_REQUIRED);					
				}
			}
		});

		//Filter toggler
		filterToggler(AppPreferences.LoadPreferenceInt("filterToggle", 0, getApplication()));
		final Button btn_toggleFilter = (Button) findViewById(R.id.btn_toggleFilter);
		btn_toggleFilter.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				LinearLayout filter = (LinearLayout) findViewById(R.id.ll_filter);
				filterToggler(filter.getVisibility());
			}
		});

		runOperationAsync(OPERATION_GET_LIST, getString(R.string.progress_loading), false);
	}
	
	
    /*
     * Override back press button(non-Javadoc)
     * @see android.app.Activity#onBackPressed()
     */
    @Override
    public void onBackPressed() {
		if(listenExtensionListSelection){
	    	listenExtensionListSelection = false;
			stripActivity(listenExtensionListSelection, lv);
		} else {
			super.onBackPressed();
		}
    }//onBackPressed
	
	
	
    /*
     * Handles requested activity result
     */
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	super.onActivityResult(requestCode, resultCode, data);
    	
    	filterToggler(AppPreferences.LoadPreferenceInt("filterToggle", 0, getApplication()));
    	
    	if(resultCode == RESPONSE_FINISH_REQUIRED){
			finishActivityWithResult(RESPONSE_FINISH_REQUIRED);
		} else if(resultCode == RESPONSE_GOTO_MAIN_ACTIVITY){
			finishActivityWithResult(RESPONSE_GOTO_MAIN_ACTIVITY);
		} else if(isFilterChanged(statusItem, dateRangeItem)){
			statusItem = AppPreferences.LoadPreferenceInt("extensionstatus", 0, getApplication());
			dateRangeItem = AppPreferences.LoadPreferenceInt("dateRange", 0, getApplication());
			runOperationAsync(OPERATION_GET_LIST, getString(R.string.progress_refreshing), false);
		} else if(requestCode == REQUEST_REFRESH_REQUIRED && resultCode == RESPONSE_REFRESH_REQUIRED){
			runOperationAsync(OPERATION_GET_LIST, getString(R.string.progress_refreshing), false); 			
		}
    	
		spinnerStatus.setSelection(statusItem);
		spinnerDateRange.setSelection(dateRangeItem);
    	
   	}//onActivityResult  
	
	
	
	/*
	 * Inflate Option menu called when menu button pressed (non-Javadoc)
	 * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.option_locationextension_list, menu);
		return true;
	}// onCreateOptionsMenu

	
	
	/*
	 * Option menu selection handler (non-Javadoc)
	 * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Intent intent;

		switch (item.getItemId()) {
			case R.id.refresh_locationextensions: 
				runOperationAsync(OPERATION_GET_LIST, getString(R.string.progress_refreshing), false);
				break;
	            
			case R.id.add_locationextension:
				showCampaignsList();
				break;
	
			case R.id.switch_account_locationextension:
				AuthService.performLogout(getApplication());
				intent = new Intent(this.getApplicationContext(), Act_Login.class);
				startActivityForResult(intent, REQUEST_REFRESH_REQUIRED);
				break;
		}
		
		return super.onOptionsItemSelected(item);
	}// onOptionsItemSelected
    
  
	
	/*
	 * Show campaigns list
	 */
	private void showCampaignsList(){
		final Dialog listDialog = new Dialog(this);
		listDialog.setTitle(R.string.title_locext_campaign_list);
		LayoutInflater li = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View v = li.inflate(R.layout.dlg_campaign_list, null, false);
		listDialog.setContentView(v);
		listDialog.setCancelable(true);
		ListView list1 = (ListView) listDialog.findViewById(R.id.list_campaign_name);
		list1.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				Map<String, String> itemMap = (Map<String, String>) arg0.getItemAtPosition(arg2);
				selectedCampaignId = itemMap.get("id");
				selectedCampaignName = itemMap.get("name");
				listDialog.dismiss();
				showExtensionAttachOption();
			}
		});
		list1.setAdapter(campaignListAdapter);
		listDialog.show();
	}//showCampaignsList
	
	
	/*
	 * Show extension selection option
	 */
	private boolean listenExtensionListSelection = false;
	private void showExtensionAttachOption(){
    	final CharSequence[] items = {
    			getString(R.string.dlg_existing_extension), 
    			getString(R.string.dlg_new_extension)
    		};

    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
    	builder.setTitle(R.string.title_locext_select_extension);
    	builder.setItems(items, new DialogInterface.OnClickListener() {
    	    public void onClick(DialogInterface dialog, int item) {
    	        
    	    	if(items[item].equals(getString(R.string.dlg_existing_extension))){
    	    		listenExtensionListSelection = true;
    	    		stripActivity(listenExtensionListSelection, lv);
    	    	}

    	    	if(items[item].equals(getString(R.string.dlg_new_extension))){
    	            Intent intent = new Intent(getBaseContext(), Act_LocationExtensionOperation.class);
    	            intent.putExtra("campaignId", selectedCampaignId);
    	            intent.putExtra("campaignName", selectedCampaignName);
    	            startActivityForResult(intent, REQUEST_NO_REFRESH_REQUIRED);
    	    	}   	    	
    	    }
    	});
    	AlertDialog alert = builder.create();
        alert.show();
	}//showExtensionAttachOption
    
    
	/*
	 * Inflate Context menu when long press occurred (non-Javadoc)
	 * @see android.app.Activity#onCreateContextMenu(android.view.ContextMenu,
	 * android.view.View, android.view.ContextMenu.ContextMenuInfo)
	 */
	Map<String, String> selectedItem;
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {

		super.onCreateContextMenu(menu, v, menuInfo);
		

		
		switch (v.getId()) {

		case R.id.list_locationextension:
			AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
			ListView list = (ListView) v;
			selectedItem = (Map<String, String>) list
					.getItemAtPosition(info.position);

			String status = selectedItem.get("status");
			
			if (status.equals("DELETED"))
				return;
			
			menu.add(0, 1, 0, R.string.locationextension_edit);

			if (!status.equals("DELETED"))
				menu.add(0, 2, 0, R.string.status_delete);

			break;
		}

		menu.setHeaderTitle(getString(R.string.tit_context_campaign));
	}// onCreateContextMenu

	
	
	/*
	 * Context menu selection handler (non-Javadoc)
	 * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
	 */
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		Intent intent;

		switch (item.getItemId()) {

		case 1:
			intent = new Intent(this.getApplicationContext(),
					Act_LocationExtensionOperation.class);
			
			intent.putExtra("extensionId", selectedItem.get("id"));
			intent.putExtra("campaignId", selectedItem.get("campaignId"));
			
			intent.putExtra("companyName", selectedItem.get("companyName"));
			intent.putExtra("streetAddress", selectedItem.get("streetAddress"));
			intent.putExtra("streetAddress2", selectedItem.get("streetAddress2"));
			intent.putExtra("cityName", selectedItem.get("cityName"));
			intent.putExtra("postalCode", selectedItem.get("postalCode"));
			intent.putExtra("countryCode", selectedItem.get("countryCode"));
			intent.putExtra("provinceName", selectedItem.get("provinceName"));
			intent.putExtra("phoneNumber", selectedItem.get("phoneNumber"));
			
			startActivityForResult(intent, REQUEST_REFRESH_REQUIRED);
			break;
			
		case 2:
			statusSetTo = STATUS_DELETED;
			
			new AlertDialog.Builder(this)
					.setTitle(R.string.msg_title_conf_delete)		
					.setMessage(getString(R.string.msg_conf_locationextension_delete) + " " + quote + selectedItem.get("streetAddress") + "..." + quote +  "?")
	    			.setPositiveButton(R.string.btn_Yes, deletionConfirmationListener)
		    		.setNegativeButton(R.string.btn_No, deletionConfirmationListener)
		    		.setCancelable(false)
		    		.create()
		    		.show();
			
			break;
		}
		return true;
	}//onContextItemSelected
	
	
	/*
	 * Dialog onClick Listener
	 */
	private DialogInterface.OnClickListener deletionConfirmationListener = new DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int which) {

			switch (which){
	        
		        case DialogInterface.BUTTON_POSITIVE:
		        	runOperationAsync(OPERATION_SET_STATUS, getString(R.string.progress_applying), false);
		            break;
	
		        case DialogInterface.BUTTON_NEGATIVE:
		        	//Do nothing on cancel
		            break;
	        }
	        
		}
	};//DialogClickListener
	
	
	
	/*
	 * Adapter for custom dialog
	 */
	private BaseAdapter campaignListAdapter = new BaseAdapter() {
		
		public int getCount() {
			int size = Act_CampaignList.campaignsList.size();
			return size;
		}

		public Object getItem(int position) {
			return Act_CampaignList.campaignsList.get(position);
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			View row = convertView;

			if (row == null) {
				LayoutInflater mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				row = mInflater.inflate(R.layout.list_row_campaign_name, null);
			}

			TextView dlg_row_campaign_id = (TextView) row.findViewById(R.id.dlg_row_campaign_id);
			TextView dlg_row_campaign_name = (TextView) row.findViewById(R.id.dlg_row_campaign_name);

			dlg_row_campaign_id.setText(Act_CampaignList.campaignsList.get(position).get("id"));
			dlg_row_campaign_name.setText(Act_CampaignList.campaignsList.get(position).get("name"));

			return row;
		}

	};
	
	
	
	/*
     * Base adapter for listview
     */
	private BaseAdapter locationExtensionListAdapter = new BaseAdapter() {

		public int getCount() {
			int size = Act_LocationExtensionList.locationExtensionList.size();
			return size;
		}

		public Object getItem(int position) {
			return Act_LocationExtensionList.locationExtensionList.get(position);
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			View row = convertView;

			if (row == null) {
				LayoutInflater mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				row = mInflater.inflate(R.layout.list_row_locationextension, null);
			}

			TextView locationextensionId = (TextView) row.findViewById(R.id.locationextensionId);
			TextView locationextension_campaignId = (TextView) row.findViewById(R.id.locationextension_campaignId);
			TextView locationextension_company_name = (TextView) row.findViewById(R.id.locationextension_company_name);
			TextView locationextension_phone_number = (TextView) row.findViewById(R.id.locationextension_phone_number);
			TextView locationextension_address_line = (TextView) row.findViewById(R.id.locationextension_address_line);
			TextView locationextension_address_line2 = (TextView) row.findViewById(R.id.locationextension_address_line2);
			TextView locationextension_city = (TextView) row.findViewById(R.id.locationextension_city);
			TextView locationextension_province_name = (TextView) row.findViewById(R.id.locationextension_province_name);
			TextView locationextension_country_code = (TextView) row.findViewById(R.id.locationextension_country_code);
			TextView locationextension_postal_code = (TextView) row.findViewById(R.id.locationextension_postal_code);
			TextView locationextension_clicks_value = (TextView) row.findViewById(R.id.locationextension_clicks_value);
			TextView locationextension_cost_value = (TextView) row.findViewById(R.id.locationextension_cost_value);
			TextView locationextension_ctr_value = (TextView) row.findViewById(R.id.locationextension_ctr_value);
			TextView locationextension_impr_value = (TextView) row.findViewById(R.id.locationextension_impr_value);
			TextView locationextension_status = (TextView) row.findViewById(R.id.locationextension_status);
			ImageView img_locationextension_status = (ImageView) row.findViewById(R.id.img_locationextension_status);
		
			locationextensionId.setText(Act_LocationExtensionList.locationExtensionList.get(position).get("id"));	
			locationextension_campaignId.setText(Act_LocationExtensionList.locationExtensionList.get(position).get("campaignId"));
			locationextension_company_name.setText(Act_LocationExtensionList.locationExtensionList.get(position).get("companyName"));
			locationextension_phone_number.setText(Act_LocationExtensionList.locationExtensionList.get(position).get("phoneNumber"));
			locationextension_address_line.setText(Act_LocationExtensionList.locationExtensionList.get(position).get("streetAddress"));
			locationextension_address_line2.setText(Act_LocationExtensionList.locationExtensionList.get(position).get("streetAddress2"));
			locationextension_city.setText(Act_LocationExtensionList.locationExtensionList.get(position).get("cityName"));
			locationextension_province_name.setText(Act_LocationExtensionList.locationExtensionList.get(position).get("provinceName"));
			locationextension_postal_code.setText(Act_LocationExtensionList.locationExtensionList.get(position).get("postalCode"));
			locationextension_country_code.setText(Act_LocationExtensionList.locationExtensionList.get(position).get("countryCode"));
			locationextension_clicks_value.setText(Act_LocationExtensionList.locationExtensionList.get(position).get("clicks"));
			locationextension_cost_value.setText(Act_LocationExtensionList.locationExtensionList.get(position).get("cost"));
			locationextension_ctr_value.setText(Act_LocationExtensionList.locationExtensionList.get(position).get("ctr"));
			locationextension_impr_value.setText(Act_LocationExtensionList.locationExtensionList.get(position).get("impressions"));
			
			String status = Act_LocationExtensionList.locationExtensionList.get(position).get("status");
			locationextension_status.setText(status);
			
			if(status.equals("ACTIVE")){
				img_locationextension_status.setImageResource(R.drawable.enable);
			} else if(status.equals("DELETED")){
				img_locationextension_status.setImageResource(R.drawable.delete);
			}

			return row;
		}
	};//campaignListAdapter

	
	/*
	 * Async operation
	 */
	private void runOperationAsync(final int operation, String message, boolean overlap) {

		//Stop if thread is alive
		if(thread.isAlive() && !overlap)
			return;
		
		//Show progress dialog
		final ProgressDialog progressDialog = ProgressDialog.show(this, "",
				message, true);

		//Check if Internet connection alive
		if(!isConnectionAvalable()){
			progressDialog.dismiss();
			return;
		}

		thread = new Thread(){
			public void run() {
				//Perform authentication
				new AuthService(Act_LocationExtensionList.this, getApplication());
				//Perform operation
				if (AuthService.authToken != null) {
					try {
						switch (operation) {
							case OPERATION_GET_LIST:
								Act_LocationExtensionList.this.obtainLocationExtensionListList();
								Act_LocationExtensionList.this.getTip();
								break;
								
							case OPERATION_SET_STATUS:
								Act_LocationExtensionList.this.setLocationExtensionStatus();
								break;				
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				//Perform postoperation
				Act_LocationExtensionList.this.runOnUiThread(new Runnable() {
					public void run() {
						
						progressDialog.dismiss();

						if (AuthService.authToken != null) {
							
							showOperationError(R.string.msg_title_error, responseErrorString);
							
							switch (operation) {
								case OPERATION_GET_LIST:
									locationExtensionListAdapter.notifyDataSetChanged();
									showStatsTotal(SHOW_TOTALS_CLICKS_COST_CTR_IMPR);
									showTip();
									break;
								
								case OPERATION_SET_STATUS:
									runOperationAsync(OPERATION_GET_LIST, getString(R.string.progress_refreshing), true);
									break;
							}
						} else {
							Intent intent = new Intent(Act_LocationExtensionList.this.getApplicationContext(),
									Act_Login.class);
							startActivityForResult(intent, REQUEST_REFRESH_REQUIRED);
						}
					}
				});
			}
		};
		thread.start(); 		
			
	}//runOperationAsync	

	
	
	/*
	 * Set Location Extension status (Delete only)
	 */
	protected void setLocationExtensionStatus() {
		String response = Communication.postSOAP(
				CampaignAdExtensionService.URL_CAMPAIGN_AD_EXTENSION_SERVICE,
				CampaignAdExtensionService.
					setLocationAdExtensionStatus(selectedItem.get("id"), 
							selectedItem.get("campaignId"), 
							statusSetTo));

		CampaignAdExtensionResponseParser parser = new CampaignAdExtensionResponseParser(response);
		
		responseErrorString = parser.checkForErrors();	
	}//setLocationExtensionStatus

	
	
	/*
	 * 
	 */
	protected void obtainLocationExtensionListList() {
		locationExtensionList.clear();

		ArrayList<String> getDateRange = DateProcessor.getDateRange(dateRangeItem);
		
		String env = CampaignAdExtensionService.getCampaignAdExtensionList(getDateRange, statusItem);
		
		String resp = Communication.postSOAP(CampaignAdExtensionService.URL_CAMPAIGN_AD_EXTENSION_SERVICE, env);
		
		CampaignAdExtensionResponseParser parser = new CampaignAdExtensionResponseParser(resp);

		locationExtensionList.addAll(parser.getLocationExtensionList());
		
		responseErrorString = parser.checkForErrors();
	}//obtainLocationExtensionListList
	
}
